//
//  BaseChatCell.swift
//  YueChat
//
//  Created by IMac on 2024/9/21.
//

import UIKit

protocol ChatCellDelegate :AnyObject {
    
    func cellTapBlock (indexPath:IndexPath)
    func cellLongBlock (indexPath:IndexPath)
    func cellCloseKeyBlock (indexPath:IndexPath)
    func cellErrorTapBlock (indexPath:IndexPath)
    func cellIconTapBlock (indexPath:IndexPath)
    func cellMulSelectBlock (indexPath:IndexPath)
    func cellLongIconBlock (indexPath:IndexPath)
}

class BaseChatCell: UITableViewCell {
    var conversation = DMCCConversation()
    weak var delegate:ChatCellDelegate?
    var indexPath:IndexPath?
//    var cellLongBlock: (() -> Void)?
//    var cellQuoteTapBlock: (() -> Void)?
//    var cellCloseKeyBlock: (() -> Void)?
//    var cellResendTapBlock: (() -> Void)?
//    var cellIconTapBlock: (() -> Void)?
//    var cellTapBlock: (() -> Void)?
//    var cellMulSelectBlock: (() -> Void)?
//    var cellLongIconBlock: (() -> Void)?
    var message = DMCCMessage()
    var myInfo = DMCCUser()
    var userInfo = DMCCUser()
    var isMulSelect = Bool()
    var chatType = Int()
    
    @IBOutlet weak var headImg: UIImageView!
    @IBOutlet weak var headImgBG: UIImageView!
    
    @IBOutlet weak var nftImg: UIImageView!
    @IBOutlet weak var msgView: UIView!
    @IBOutlet weak var leftMsg: NSLayoutConstraint!
    @IBOutlet weak var topMsg: NSLayoutConstraint!
    @IBOutlet weak var msgViewTop: NSLayoutConstraint!

    
    
    private(set) lazy var tapBlock: UITapGestureRecognizer = {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(tapBtnClick))
        return gesture
    }()
    
    private(set) lazy var closeKeyGes: UITapGestureRecognizer = {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(tapCloseKeyClick))
        return gesture
    }()
    
    private(set) lazy var iconTapGes: UITapGestureRecognizer = {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(iconTapClick))
        return gesture
    }()
    
    private(set) lazy var longIconGes: UILongPressGestureRecognizer = {
        let gesture = UILongPressGestureRecognizer(target: self, action: #selector(longIconPressAction(_:)))
        return gesture
    }()
    
    private(set) lazy var longGes: UILongPressGestureRecognizer = {
        let gesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
        return gesture
    }()
    
    private(set) lazy var mulView: UIView = {
        let view = UIView()
        view.isHidden = true
        return view
    }()
    
    private(set) lazy var mulTapGes: UITapGestureRecognizer = {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(mulTapClick))
        return gesture
    }()
    
    private(set) lazy var resendTapGes: UITapGestureRecognizer = {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(resendTapClick))
        return gesture
    }()
    
    private(set) lazy var mulBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "select_n"), for: .normal)
        button.setImage(UIImage(named: "select_s"), for: .selected)
        button.isUserInteractionEnabled = false
        return button
    }()
    
    private(set) lazy var errorImg: UIImageView = {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        imageView.image = UIImage(named: "warning")
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
 
    
    private(set) lazy var readImg: UIImageView = {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    lazy var timeLabel: UILabel = {
        let timeLabel = UILabel(frame:CGRect(x: 0, y: 0, width: kScreenWidth, height: 20))
        timeLabel.font = UIFont.systemFont(ofSize: 12)
        timeLabel.textColor = .gray
        timeLabel.textAlignment = .center
         return timeLabel
     }()
    
    private(set) lazy var nickNameLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = .clear
        label.textColor = UIColor.black
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        
        self.contentView.backgroundColor = UIColor.clear
        self.backgroundColor = UIColor.clear
        self.selectionStyle = .none
        
        guard let msgView = msgView  else {
            return
        }
//        msgView.backgroundColor = kMainColor
        msgView.layer.masksToBounds = true
        msgView.layer.cornerRadius = 5
        

        
        addSubview(errorImg)
        addSubview(readImg)
        addSubview(nickNameLabel)
        addSubview(mulView)
        
        addGestureRecognizer(closeKeyGes)
        
        headImg.layer.masksToBounds = true
        headImg.layer.cornerRadius = 5
        headImg.isUserInteractionEnabled = true
        headImg.addGestureRecognizer(iconTapGes)
        headImg.addGestureRecognizer(longIconGes)
        
        mulView.addGestureRecognizer(mulTapGes)
        
        msgView.addGestureRecognizer(tapBlock)
        msgView.addGestureRecognizer(longGes)
        errorImg.addGestureRecognizer(resendTapGes)
        
        addSubview(timeLabel)

        nickNameLabel.snp.makeConstraints { make in
            make.top.equalTo(headImgBG)
                //水平居中
            make.left.equalTo(headImg.snp.right).offset(8)
        }

        
        
        mulView.addSubview(mulBtn)
        
        mulView.snp.makeConstraints { make in
//            make.edges.equalTo(self.contentView.snp.edges)
            make.width.equalTo(100)
                make.height.equalTo(100)
                
                //距离顶部
                make.top.equalTo(100)
                
                //水平居中
                make.centerX.equalToSuperview()
        }
        
        mulBtn.snp.makeConstraints { make in
            make.left.equalTo(self.mulView).offset(15)
            make.centerY.equalTo(self.mulView);
            make.width.height.equalTo(20)
        }
    }
    
    @objc func tapCloseKeyClick() {
        delegate?.cellCloseKeyBlock(indexPath: indexPath!)
    }
    
    @objc func resendTapClick() {
        delegate?.cellErrorTapBlock(indexPath: indexPath!)
    }
    
    @objc func iconTapClick() {
        delegate?.cellIconTapBlock(indexPath: indexPath!)
    }
    
    @objc func tapBtnClick() {
        delegate?.cellTapBlock(indexPath: indexPath!)
    }
    
    @objc func mulTapClick() {
        delegate?.cellMulSelectBlock(indexPath: indexPath!)
    }
    
    @objc func longIconPressAction(_ longPress: UILongPressGestureRecognizer) {
        if longPress.state == .began {
            delegate?.cellLongIconBlock(indexPath: indexPath!)
        }
    }
    
    @objc func longPressAction(_ longPress: UILongPressGestureRecognizer) {
        if longPress.state == .began {
            delegate?.cellLongBlock(indexPath: indexPath!)
        }
    }


    // MARK: - Methods
    func setChatType(_ type: Int, myInfo: DMCCUser?, userInfo: DMCCUser?, withConversation conversation: DMCCConversation) {
        chatType = type
        self.myInfo = myInfo!
        self.userInfo = userInfo!
        self.conversation = conversation
    }
    
    func baseCellHeight(message: DMCCMessage, chatType: Bool, mulSelect: Bool, isMySend: Bool) {
        message.msgCellHeight = 0
    }
    
    func setIsMulSelect(_ isMulSelect: Bool) {
        self.isMulSelect = isMulSelect
    }
    
    func setMessage(_ message: DMCCMessage) {
        self.message = message
        
        if message.content is OsnNotifyContent {
            return
        }
        
        if message.status == .Send_Failure {
            errorImg.isHidden = false
            readImg.isHidden = true
        } else {
            errorImg.isHidden = true
            if message.direction == .Send {
                readImg.isHidden = false
            } else {
                readImg.isHidden = true
            }
        }
        
        let timeStr = formatTimeDetailLabel(timestamp: message.timestamp)
        timeLabel.text = timeStr
        
        // 时间
        if message.showTime {
            
            if  message.direction == .Send {
                topMsg.constant = -30
            }else{
                topMsg.constant = 30
            }
            timeLabel.isHidden = false
        } else {
            
            if  message.direction == .Send {
                topMsg.constant = -10
            }else{
                topMsg.constant = 10
            }
           
            timeLabel.isHidden = true
        }
        
        timeLabel.layoutIfNeeded()

        
        
        
        
        if message.direction == .Send {
            nickNameLabel.isHidden = true
            self.headImg.sd_setImage(with: URL(string: myInfo.portrait), placeholderImage: SDImageDefault)
//            make.left.equalTo(self.mulView).offset(15)
            self.errorImg.snp.makeConstraints { make in
                make.right.equalTo(self.msgView.snp.left).offset(-15)
//                make.right.equalTo()(self.msgView)?.setOffset(-15)
                make.centerY.equalTo(self.msgView.snp.centerY)
                make.width.height.equalTo(20)
            }
        } else {
            
            
            //let type = ConversationInfo.getType(con?.targetId ?? "")
            if conversation.type == .Group {
                let group = gosnGroup.getGroupInfoDefault(conversation.targetId)
                
                let userInfo = message.originalUser.isEmpty ? nil : gosnUser.getUserInfo(message.originalUser)
                
                let isHiddenNickName = group.showAlias
                
                nickNameLabel.isHidden = !isHiddenNickName
                if isHiddenNickName {
                    self.nickNameLabel.text = userInfo?.getAlias()
                    if chatType == conversation.type.rawValue {
                        nickNameLabel.text = userInfo?.getAlias()
          
                        msgViewTop.constant = 22
                    }
                }else {
                    msgViewTop.constant = 1
                }
            }
        }
        
        if !(message.content is OsnNotifyContent) {
            if isMulSelect {
                mulView.isHidden = false
                
                mulBtn.isSelected = message.uiData as? String ?? "" == "1"
                if message.direction == .Receive {
                    leftMsg.constant = 50
                }
            } else {
                mulView.isHidden = true
                if message.direction == .Receive {
                    leftMsg.constant = 15
                }
                
            }
        }
        
        var user = DMCCUser()
        if message.getFrom() == myInfo.userId {
            user = gosnUser.getUserInfoDefault(myInfo.userId)
        } else if message.originalUser.count > 0 {
            user = gosnUser.getUserInfoDefault(message.originalUser)
        } else {
            user = gosnUser.getUserInfoDefault(message.target)
        }
        self.headImg.sd_setImage(with: URL(string: user.portrait), placeholderImage: SDImageDefault)
        let nftStr = user.getNft()
        self.nftImg.isHidden = nftStr!.isEmpty
        if chatType == 0 {
            self.headImgBG.isHidden = true
        } else {
            self.headImgBG.isHidden = false
            
            guard let gm = gosnMember.getMemberInfo(conversation.targetId, user.userId) else {
                return
            }
            switch gm.type {
            case .Owner:
                self.headImgBG.image = UIImage(named: "member_main")
            case .Admin:
                self.headImgBG.image = UIImage(named: "member_manager")
            default:
                self.headImgBG.image = UIImage(named: "member_nomal")
            }
        }
    }
    
    // MARK: - Getter
  

    
//    private(set) var _timeLabel: UILabel?
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

